import request from './index'
import Store from './../store/index'
// import config from './../../static/config/config'
// let axiosDate = new Date()
let host_news = config.host_news
let host_picking = config.host_pingking
let host_quote = config.host_quote
const URL = {
  getHotNews: `${host_news}/hot-news`,
  getAllFactors: `${host_picking}/factors`,
  getNewFactor: `${host_picking}/latest_factors`,
  getHotFactor: `${host_picking}/hot_factors`,
  getTopFactor: `${host_picking}/top_factors`,
  getStockCodes: `${host_picking}/stocks`,
  getStockQuote: `${host_quote}`,
  getNewStockQuote: `${host_quote}`,
  getHotTypeFactors: `${host_picking}/hot_type_factors`,
  searchAllFactors: `${host_picking}/factors/search`,
  allMyStrategys: `${host_picking}`,
  addMyStrategys: `${host_picking}`,
  delMyStrategys: `${host_picking}`,
  reMyStrategys: `${host_picking}`,
  getBestStocks: `${host_picking}/best_three_stocks`,
  getBanner: 'http://api-cm.zhangtl.com:8000/json/cczq-banner.json'
}

class REQUEST {
  constructor({request, URL}) {
    this.URL = URL
    this.request = request
    this.getAllFactors = this.getAllFactors.bind(this)
    this.searchAllFactors = this.searchAllFactors.bind(this)
    this.getNewFactor = this.getNewFactor.bind(this)
    this.getHotNews = this.getHotNews.bind(this)
    this.getTopFactor = this.getTopFactor.bind(this)
    this.getStockQuote = this.getStockQuote.bind(this)
    this.getNewStockQuote = this.getNewStockQuote.bind(this)
    this.allMyStrategys = this.allMyStrategys.bind(this)
    this.addMyStrategys = this.addMyStrategys.bind(this)
    this.getHotTypeFactors = this.getHotTypeFactors.bind(this)
    this.getBanner = this.getBanner.bind(this)
  }

  /**
   * 获取所有因子
   * @returns {*}
   */
  getAllFactors() {
    let url = URL.getAllFactors
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url)
  }

  /**
   *  搜所因子
   * @param _key [String] eg:'规划' 【中文】
   * @returns {*}
   */
  searchAllFactors(_key) {
    let url = URL.searchAllFactors
    let params = {
      keyword: _key
    }
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url, {params})
  }

  getHotTypeFactors(_type) {
    let url = URL.getHotTypeFactors
    let params = {
      type: _type
    }
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url, {params})
  }

  /**
   * 获取最新因子
   * @param _url
   * @returns {*}
   */
  getNewFactor(_url) {
    let url = URL.getNewFactor
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url)
  }

  /**
   *  获取置顶因子
   * @param _url
   * @returns {*}
   */
  getTopFactor(_url) {
    let url = URL.getTopFactor
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url)
  }

  /**
   * 获取热门因子
   * @param _url
   * @returns {*}
   */
  getHotFactor({count, days}) {
    let url = URL.getHotFactor
    let params = {
      count: count,
      days: days
    }
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url, {params})
  }

  /**
   * 获取新闻资讯
   * @param _url
   * @returns {*}
   */
  getHotNews(_url) {
    let url = URL.getHotNews
    url = url + _url
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url)
  }

  /**
   *  新建策略
   * @param _userId [String]    eg: '17620480922'（长城以手机号为用户id）
   * @param _strategyName [String] eg: '策略一'
   * @param _factorIds  [String] eg: '1818,1817'
   * @returns {*}
   */
  addMyStrategys(_userId, _strategyName, _factorIds) {
    let url = URL.addMyStrategys + '/' + _userId.mobilecode + '/strategy'
    let params = {
      strategy_name: _strategyName,
      factor_ids: _factorIds
    }
    // console.log(url, params)
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.POST(url, params)
  }

  /**
   *  删除策略
   * @param _userInfo
   * @param _strategy
   * @returns {*}
   */
  delMyStrategys(_userInfo, _strategy) {
    let url = URL.delMyStrategys + '/' + _userInfo.mobilecode + '/strategies/' + _strategy.strategy_id
    let params = {
      strategy_name: _strategy.strategy_name,
      factor_ids: _strategy.factor_ids,
      action: 1
    }
    // console.log(url, params)
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.PUT(url, params)
  }

  /**
   *  修改策略
   * @param _userInfo
   * @param _strategy
   * @returns {*}
   */
  relMyStrategys(_userInfo, _strategy) {
    let url = URL.delMyStrategys + '/' + _userInfo.mobilecode + '/strategies/' + _strategy.strategy_id
    let params = {
      strategy_name: _strategy.strategy_name,
      factor_ids: _strategy.factor_ids,
      action: 0
    }
    // console.log(url, params)
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.PUT(url, params)
  }

  /**
   *  获取所有策略（用户）
   * @param _userId
   * @returns {*}
   */
  allMyStrategys(_userId) {
    let url = URL.allMyStrategys + '/' + _userId.mobilecode + '/strategies'
    // console.log(url)
    return request.GET(url)
  }

  getBestStocks(_info) {
    let url = URL.getBestStocks
    // console.log(encodeURI(_info))
    let params = {
      factor_names: _info
    }
    return request.GET(url, {params})
  }

  /**
   *  获取所选因子对应股票代码
   * @param _code [String] eg:'1817,1816'
   * @param _page [Number]
   * @param _count [Number]
   * @returns {*}
   */
  getStockCodes(_code, _page, _count) {
    // console.log(_code, _page, _count)
    let url = URL.getStockCodes
    let params = {
      factors: _code,
      page_index: _page,
      page_size: _count
    }
    return request.GET(url, {params})
  }

  /**
   * 获取股票行情 (长城) ----old
   *  dealStockLink 拼接key和value
   *  splitStockCode
   * @param _code
   */
  getStockQuote(_code) {
    let url = URL.getStockQuote
    let _data = {
      id: '1',
      jsonrpc: '2.0',
      method: 'GetZqHqJbt',
      // params: ['0', 'SZ000002']
      params: []
    }

    function dealStockLink(_key, _val) {
      let result = {}
      for (let i = 0; i < _key.length; i++) {
        if (_val) {
          result[_key[i]] = _val[i]
        } else {
          result[_key[i][0]] = _key[i][1]
        }
      }
      return result
    }

    function splitStockCode(_id) {
      let _arr = _id.split(',')
      let d = ['0']
      let b, c
      for (let i = 0; i < _arr.length; i++) {
        b = _arr[i].split('.')
        c = b[1] + b[0]
        d.push(c)
      }
      return d
    }

    _data.params = splitStockCode(_code)
    return request.POST(url, _data).then(res => {
      let newData = []
      for (let i = 1; i < res.result.length; i++) {
        newData.push(dealStockLink(res.result[0], res.result[i]))
      }
      return newData
    })
  }

  /**
   *  获取股票行情 (长城) ----new
   *  _keyNM =>
   *  stock_name 股票名称
   *  stock_code 股票代码
   *  last_price 最新价
   *  zd 涨跌
   *  fd 幅度
   *  pe 市盈率（静）
   *  stock_industry 所属行业
   *  su_sign 停牌标志
   *  suspend 停牌状态
   * @param _strCode [String]  eg: '600600.SH,300624.SZ'
   * @param _count [Number]
   * @returns {*|PromiseLike<T>|Promise<T>}
   */
  getNewStockQuote(_strCode, _count, _accountIndex, _direction) {
    let url = URL.getNewStockQuote
    let _keyNM = ['stock_name', 'stock_code', 'last_price', 'zd', 'fd', 'pe', 'stock_industry', 'su_sign', 'suspend']
    _strCode = _strCode.replace(/\./g, '|')
    let params = {
      action: 60,
      grid: _strCode,
      maxcount: _count,
      StockIndex: 6,
      NeedCheck: '1|32|2|3|4|92|241|209|210|'
    }
    if (!(typeof _accountIndex === 'undefined' && typeof _direction === 'undefined')) {
      params.AccountIndex = _accountIndex
      params.Direction = _direction
    }

    function dealStockLink(_key, _val) {
      let result = {}
      for (let i = 0; i < _key.length; i++) {
        if (_val) {
          result[_key[i]] = _val[i]
        } else {
          result[_key[i][0]] = _key[i][1]
        }
      }
      return result
    }

    return request.GET(url, {params}).then(res => {
      let newData = []
      for (let i = 1; i < res.GRID0.length; i++) {
        let _keyt = res.GRID0[0].split('|')
        let _keyc = res.GRID0[i].split('|')
        _keyt.pop()
        _keyc.pop()
        for (let j = 0; j < _keyt.length; j++) {
          _keyt[j] = _keyNM[j]
        }
        _keyc[0] = _keyc[0].split('.')[1]
        newData.push(dealStockLink(_keyt, _keyc))
      }
      return newData
    })
  }

  /**
   *  获取轮播图片
   * @returns {*}
   */
  getBanner () {
    let url = URL.getBanner
    if(window.location.href) {
      Store.dispatch('fetchLoading', true)
    }
    request.axiosDate = new Date()
    return request.GET(url)
  }
}

export default new REQUEST({request, URL})
